package com.coocaa.ops.common.tool.math;

import com.coocaa.ops.common.tool.date.DateUtil;

import java.util.Random;

/**
 * @author bijiahao
 * @date : 2019/7/18.
 * @description
 */
public final class RandomUtil {
    private static final String SRC_NUMBER = "0123456789";
    private static final String SRC_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String SRC_UPPER = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
    private static final String SRC_HEX_LOWER = "0123456789abcdef";
    private static final String SRC_HEX_UPPER = "0123456789abcdef".toUpperCase();
    private static final String ESC_CHAR = "?";

    private RandomUtil() {
    }

    public static String getRandomLongStr() {
        String str = DateUtil.getCurrentDateStr("yyyyMMddHHmmss") + getRandNo(6);
        return str;
    }

    public static String getRandNo(int dit) {
        StringBuffer sb = new StringBuffer("");
        Random random = new Random();

        for (int i = 0; i < dit; ++i) {
            sb.append(random.nextInt(10));
        }

        return sb.toString();
    }

    public static String get(int size) {
        StringBuffer r = new StringBuffer(size);
        String src =SRC_NUMBER + SRC_UPPER;

        for (int i = 0; i < size; ++i) {
            r.append(getRandomChar(src));
        }

        return r.toString();
    }

    public static String get(String format) {
        StringBuffer r = new StringBuffer(format.length());
        String src = SRC_NUMBER + SRC_UPPER;

        for (int i = 0; i < format.length(); ++i) {
            String curr = String.valueOf(format.charAt(i));
            if (curr.equalsIgnoreCase("?")) {
                r.append(getRandomChar(src));
            } else {
                r.append(curr);
            }
        }

        return r.toString();
    }

    public static String get(String format, char esc) {
        StringBuffer r = new StringBuffer(format.length());
        String src = SRC_NUMBER + SRC_UPPER;

        for (int i = 0; i < format.length(); ++i) {
            String curr = String.valueOf(format.charAt(i));
            if (curr.equalsIgnoreCase(String.valueOf(esc))) {
                r.append(getRandomChar(src));
            } else {
                r.append(curr);
            }
        }

        return r.toString();
    }

    public static String getNum(int size) {
        StringBuffer r = new StringBuffer(size);
        for (int i = 0; i < size; ++i) {
            r.append(getRandomChar(SRC_NUMBER));
        }

        return r.toString();
    }

    private static final String getRandomChar(String src) {
        return null != src && !"".equals(src) ? String.valueOf(src.charAt((int) (Math.random() * (double) src.length()))) : "";
    }


}
